// main.js - 完整的SMS验证码服务 for Deno Deploy

// 北京时间处理函数
function getBeijingTime(timestamp = null) {
  const date = timestamp ? new Date(timestamp) : new Date();
  // 北京时间 = UTC时间 + 8小时
  const beijingTime = new Date(date.getTime() + (8 * 60 * 60 * 1000));
  return {
    timestamp: beijingTime.getTime(),
    formatted: beijingTime.getFullYear() + '/' + 
               String(beijingTime.getMonth() + 1).padStart(2, '0') + '/' + 
               String(beijingTime.getDate()).padStart(2, '0') + ' ' +
               String(beijingTime.getHours()).padStart(2, '0') + ':' +
               String(beijingTime.getMinutes()).padStart(2, '0') + ':' +
               String(beijingTime.getSeconds()).padStart(2, '0'),
    iso: beijingTime.toISOString().replace('T', ' ').substring(0, 19) + ' (北京时间)'
  };
}

class SMSCodeManager {
  constructor() {
    this.codes = [];
    this.maxAge = 5 * 60 * 1000; // 5分钟过期
  }

  // 添加验证码
  async addCode(message, sender = '', code = '') {
    // 如果已有提取的验证码就直接使用，否则从消息中提取
    const extractedCode = code || this.extractCode(message);
    
    if (extractedCode) {
      const smsData = {
        code: extractedCode,
        message: message,
        sender: sender,
        timestamp: Date.now(),
        used: false,
        usedBy: null // 新增：记录使用者信息
      };
      
      // 保存到KV存储
      await saveSMSToKV(smsData);
      
      // 同时保存到内存（向后兼容）
      this.codes.push(smsData);
      
      const beijingTime = getBeijingTime(smsData.timestamp);
      console.log(`📱 收到验证码: ${extractedCode} from ${sender} at ${beijingTime.formatted}`);
      
      if (DEBUG_MODE) {
        console.log(`💾 已保存到KV存储和内存`);
      }
      return extractedCode;
    }
    return null;
  }

  // 提取验证码的正则表达式（兼容多种格式）
  extractCode(text) {
    const patterns = [
      /验证码[：:]?(\d{6})/,
      /验证码为[：:]?(\d{6})/,
      /验证码是[：:]?(\d{6})/,
      /验证码.*?(\d{6})/,
      /code[：:]?(\d{6})/i,
      /(\d{6})/
    ];

    for (const pattern of patterns) {
      const match = text.match(pattern);
      if (match && match[1]) {
        return match[1];
      }
    }
    return null;
  }

  // 格式化过期时间显示
  formatExpiredDuration(durationMs) {
    const totalSeconds = Math.floor(durationMs / 1000);
    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const seconds = totalSeconds % 60;
    
    if (hours > 0) {
      return `${hours}小时${minutes}分钟${seconds}秒前过期`;
    } else if (minutes > 0) {
      return `${minutes}分钟${seconds}秒前过期`;
    } else {
      return `${seconds}秒前过期`;
    }
  }

  // 格式化User-Agent显示
  formatUserAgent(userAgent) {
    if (!userAgent || userAgent === 'unknown') {
      return '未知';
    }
    
    // 提取主要浏览器信息
    if (userAgent.includes('Chrome')) {
      const chromeMatch = userAgent.match(/Chrome\/([0-9\.]+)/);
      return chromeMatch ? `Chrome ${chromeMatch[1].split('.')[0]}` : 'Chrome';
    } else if (userAgent.includes('Firefox')) {
      const firefoxMatch = userAgent.match(/Firefox\/([0-9\.]+)/);
      return firefoxMatch ? `Firefox ${firefoxMatch[1].split('.')[0]}` : 'Firefox';
    } else if (userAgent.includes('Safari') && !userAgent.includes('Chrome')) {
      return 'Safari';
    } else if (userAgent.includes('Edge')) {
      return 'Edge';
    } else if (userAgent.includes('Loon-SMS-Forwarder')) {
      return 'Loon插件';
    } else {
      // 如果无法识别，返回简化版本
      return userAgent.length > 20 ? userAgent.substring(0, 20) + '...' : userAgent;
    }
  }

  // 获取最新未使用的验证码
  async getLatestCode(userInfo = {}) {
    // 从KV存储获取所有验证码
    const allCodes = await getAllSMSFromKV();
    
    // 清理过期验证码
    await cleanExpiredSMSFromKV(this.maxAge);
    
    const now = Date.now();
    
    // 获取最新的可用验证码（未使用且未过期）
    const availableCodes = allCodes.filter(sms => {
      const isNotUsed = !sms.used;
      const isNotExpired = (now - sms.timestamp) < this.maxAge;
      return isNotUsed && isNotExpired;
    });
    
    if (availableCodes.length > 0) {
      const latest = availableCodes[0]; // 取第一个（最新的）
      latest.used = true; // 标记为已使用
      latest.usedBy = {
        ip: userInfo.ip || 'unknown',
        userAgent: userInfo.userAgent || 'unknown',
        timestamp: Date.now(),
        beijingTime: getBeijingTime().formatted
      };
      
      // 更新KV存储
      await updateSMSInKV(latest);
      
      const beijingTime = getBeijingTime();
      console.log(`🎯 返回验证码: ${latest.code} to ${userInfo.ip || 'unknown'} at ${beijingTime.formatted}`);
      return latest.code;
    }
    
    console.log(`⚠️ 没有可用的验证码（总计${allCodes.length}条，可用${availableCodes.length}条）`);
    return null;
  }

  // 清理过期验证码
  cleanExpiredCodes() {
    const now = Date.now();
    const originalLength = this.codes.length;
    
    this.codes = this.codes.filter(sms => 
      (now - sms.timestamp) < this.maxAge
    );

    if (this.codes.length < originalLength) {
      const beijingTime = getBeijingTime();
      console.log(`🧹 清理了 ${originalLength - this.codes.length} 个过期验证码 at ${beijingTime.formatted}`);
    }
  }

  // 获取所有验证码状态（调试用）
  async getStatus() {
    // 从KV存储获取所有验证码
    const allCodes = await getAllSMSFromKV();
    const now = Date.now();
    
    if (DEBUG_MODE) {
      console.log(`🔍 getStatus调用 - 从KV获取到 ${allCodes.length} 条验证码`);
    }
    
    const processedCodes = allCodes.map(sms => {
      const beijingTime = getBeijingTime(sms.timestamp);
      const remainingTime = Math.max(0, this.maxAge - (now - sms.timestamp));
      const expired = remainingTime <= 0;
      
              return {
          code: sms.code,
          sender: sms.sender,
          timestamp: beijingTime.formatted,
          used: sms.used,
          usedBy: sms.usedBy,
          age: Math.floor((now - sms.timestamp) / 1000) + 's',
          remainingTime: Math.floor(remainingTime / 1000), // 剩余秒数
          expired: expired,
          expiredDuration: expired ? this.formatExpiredDuration(now - sms.timestamp - this.maxAge) : null
        };
    });
    
    // 修复：可用数量应该排除已使用和已过期的验证码
    const available = processedCodes.filter(sms => !sms.used && !sms.expired).length;
    
    return {
      total: allCodes.length,
      available: available,
      codes: processedCodes
    };
  }

  // 获取24小时内使用统计
  async getUsageStats() {
    // 从KV存储获取所有验证码
    const allCodes = await getAllSMSFromKV();
    const now = Date.now();
    const oneDayAgo = now - (24 * 60 * 60 * 1000);
    
    // 过滤24小时内的验证码
    const recentCodes = allCodes.filter(sms => sms.timestamp > oneDayAgo);
    
    const used = recentCodes.filter(sms => sms.used);
    // 未使用的验证码还要检查是否过期
    const unused = recentCodes.filter(sms => {
      const isNotUsed = !sms.used;
      const isNotExpired = (now - sms.timestamp) < this.maxAge;
      return isNotUsed && isNotExpired;
    });
    
    return {
      total: recentCodes.length,
      used: {
        count: used.length,
        codes: used.map(sms => ({
          code: sms.code,
          sender: sms.sender,
          receivedAt: getBeijingTime(sms.timestamp).formatted,
          usedAt: sms.usedBy ? sms.usedBy.beijingTime : '未知',
          usedBy: sms.usedBy ? {
            ip: sms.usedBy.ip || 'unknown',
            time: sms.usedBy.beijingTime || '未知',
            userAgent: this.formatUserAgent(sms.usedBy.userAgent)
          } : {
            ip: 'unknown',
            time: '未知',
            userAgent: '未知'
          }
        }))
      },
      unused: {
        count: unused.length,
        codes: unused.map(sms => {
          const remainingTime = Math.max(0, this.maxAge - (now - sms.timestamp));
          return {
            code: sms.code,
            sender: sms.sender,
            receivedAt: getBeijingTime(sms.timestamp).formatted,
            expiresAt: getBeijingTime(sms.timestamp + this.maxAge).formatted,
            remainingSeconds: Math.floor(remainingTime / 1000),
            expired: remainingTime <= 0
          };
        })
      }
    };
  }
}

// 初始化Deno KV存储
const kv = await Deno.openKv();

// KV存储操作函数
async function saveSMSToKV(smsData) {
  try {
    // 使用北京时间作为key，精确到秒
    const beijingTime = getBeijingTime(smsData.timestamp);
    const timeKey = beijingTime.formatted.replace(/[\/\s:]/g, '_'); // 2025_01_16_10_30_45
    const key = ["sms", timeKey];
    
    // 设置30天过期时间
    const expireIn = 30 * 24 * 60 * 60 * 1000; // 30天毫秒数
    await kv.set(key, smsData, { expireIn });
    
    if (DEBUG_MODE) {
      console.log(`💾 验证码已保存到KV: ${smsData.code}, key: ${timeKey}`);
    }
    return true;
  } catch (error) {
    console.error('❌ KV保存失败:', error);
    return false;
  }
}

async function getAllSMSFromKV() {
  try {
    const entries = [];
    const iter = kv.list({ prefix: ["sms"] });
    for await (const entry of iter) {
      entries.push(entry.value);
    }
    // 按时间戳倒序排序（最新的在前面）
    entries.sort((a, b) => b.timestamp - a.timestamp);
    
    if (DEBUG_MODE) {
      console.log(`📖 从KV读取到 ${entries.length} 条验证码`);
    }
    return entries;
  } catch (error) {
    console.error('❌ KV读取失败:', error);
    return [];
  }
}

async function updateSMSInKV(smsData) {
  try {
    // 使用北京时间作为key，精确到秒
    const beijingTime = getBeijingTime(smsData.timestamp);
    const timeKey = beijingTime.formatted.replace(/[\/\s:]/g, '_');
    const key = ["sms", timeKey];
    
    // 保持30天过期时间
    const expireIn = 30 * 24 * 60 * 60 * 1000;
    await kv.set(key, smsData, { expireIn });
    
    if (DEBUG_MODE) {
      console.log(`🔄 验证码状态已更新: ${smsData.code}`);
    }
    return true;
  } catch (error) {
    console.error('❌ KV更新失败:', error);
    return false;
  }
}

async function cleanExpiredSMSFromKV(maxAge) {
  try {
    const now = Date.now();
    const entries = await getAllSMSFromKV();
    let cleanedCount = 0;
    
    for (const sms of entries) {
      if ((now - sms.timestamp) >= maxAge) {
        const beijingTime = getBeijingTime(sms.timestamp);
        const timeKey = beijingTime.formatted.replace(/[\/\s:]/g, '_');
        const key = ["sms", timeKey];
        await kv.delete(key);
        cleanedCount++;
      }
    }
    
    if (cleanedCount > 0 && DEBUG_MODE) {
      console.log(`🧹 从KV清理了 ${cleanedCount} 个过期验证码`);
    }
    return cleanedCount;
  } catch (error) {
    console.error('❌ KV清理失败:', error);
    return 0;
  }
}

// 创建SMS管理器实例
const smsManager = new SMSCodeManager();

// 获取访问令牌
const ACCESS_TOKEN = Deno.env.get('ACCESS_TOKEN') || 'fysms2024';

// 调试开关（默认关闭）
const DEBUG_MODE = Deno.env.get('DEBUG_MODE') === 'true' || false;

// 获取客户端真实IP地址
function getClientIP(request) {
  return request.headers.get('cf-connecting-ip') || 
         request.headers.get('x-forwarded-for') || 
         request.headers.get('x-real-ip') || 
         'unknown';
}

// HTTP请求处理器
async function handleRequest(request) {
  const url = new URL(request.url);
  const method = request.method;

  // 设置CORS头
  const corsHeaders = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type, User-Agent',
    'Content-Type': 'application/json; charset=utf-8'
  };

  // 处理OPTIONS预检请求
  if (method === 'OPTIONS') {
    return new Response(null, { status: 200, headers: corsHeaders });
  }

  try {
    // 接收短信验证码 - iOS Loop + getsms.js 调用
    if (url.pathname === '/sms' && method === 'POST') {
      const beijingTime = getBeijingTime();
      // 添加更详细的日志
      console.log(`🔍 收到POST请求到 /sms at ${beijingTime.formatted}`);
      console.log('📋 请求URL:', request.url);
      console.log('📋 请求方法:', method);
      console.log('📋 请求头:', Object.fromEntries(request.headers.entries()));
      console.log('📋 User-Agent:', request.headers.get('user-agent') || 'N/A');
      console.log('📋 Content-Type:', request.headers.get('content-type') || 'N/A');
      
      let body;
      let text = '';
      try {
        text = await request.text();
        console.log('📥 原始请求体长度:', text.length);
        console.log('📥 原始请求体:', text);
        
        if (text.trim() === '') {
          console.log('⚠️ 请求体为空');
          return new Response(JSON.stringify({
            success: false,
            error: '请求体为空',
            timestamp: beijingTime.formatted,
            beijing_time: beijingTime.iso,
            debug_info: {
              content_length: text.length,
              headers: Object.fromEntries(request.headers.entries())
            }
          }), { status: 400, headers: corsHeaders });
        }
        
        body = JSON.parse(text);
        console.log('📦 解析后数据:', JSON.stringify(body, null, 2));
      } catch (error) {
        console.error('❌ 解析请求体失败:', error);
        console.log('📥 失败的原始内容:', text.substring(0, 500));
        return new Response(JSON.stringify({
          success: false,
          error: '请求体格式错误: ' + error.message,
          received: text.substring(0, 200),
          timestamp: beijingTime.formatted,
          beijing_time: beijingTime.iso,
          debug_info: {
            error_type: error.name,
            error_message: error.message,
            content_preview: text.substring(0, 100)
          }
        }), { status: 400, headers: corsHeaders });
      }
      
      let message, sender, code;
      
      // 兼容Loon短信格式
      if (body.source === 'loon_sms') {
        message = body.message || '';
        sender = body.sender || '';
        code = body.code || '';
        console.log('✅ 识别为Loon短信格式');
      } else if (body.source === 'chenxing_sms') {
        message = body.message || '';
        sender = body.sender || '';
        code = body.code || '';
        console.log('✅ 识别为辰星短信格式');
      } else {
        message = body.message || body.text || body.content || JSON.stringify(body);
        sender = body.sender || body.from || 'Unknown';
        code = '';
        console.log('⚠️ 使用通用格式解析');
      }
      
      const finalCode = await smsManager.addCode(message, sender, code);
      console.log('🎯 最终提取的验证码:', finalCode);
      
      if (DEBUG_MODE) {
        // 调试：检查当前验证码状态
        const debugStatus = await smsManager.getStatus();
        console.log('🔍 当前验证码总数:', debugStatus.total);
        console.log('🔍 可用验证码数:', debugStatus.available);
        console.log('🔍 验证码列表:', debugStatus.codes.map(c => `${c.code}(${c.used ? '已用' : '未用'})`));
      }
      
      const responseTime = getBeijingTime();
      return new Response(JSON.stringify({
        success: true,
        code: finalCode,
        message: finalCode ? '验证码已接收并处理' : '未能提取验证码',
        timestamp: responseTime.formatted,
        beijing_time: responseTime.iso,
        debug_info: {
          original_message: message,
          sender: sender,
          extracted_code: finalCode,
          source: body.source || 'unknown',
          received_at: responseTime.formatted
        }
      }), { headers: corsHeaders });
    }

    // 获取验证码 - Automa调用（需要token验证）
    if (url.pathname === '/get_code' && method === 'GET') {
      const beijingTime = getBeijingTime();
      const clientIP = getClientIP(request);
      const userAgent = request.headers.get('user-agent') || 'unknown';
      
      // 验证访问令牌
      const token = url.searchParams.get('token');
      if (!token || token !== ACCESS_TOKEN) {
        console.log(`🚫 未授权访问 /get_code from ${clientIP} at ${beijingTime.formatted}`);
        return new Response(JSON.stringify({
          error: '访问被拒绝',
          message: '需要有效的访问令牌',
          status: 'unauthorized',
          timestamp: beijingTime.formatted,
          beijing_time: beijingTime.iso
        }), { 
          status: 401, 
          headers: corsHeaders 
        });
      }
      
      // 记录访问信息并获取验证码
      const userInfo = {
        ip: clientIP,
        userAgent: userAgent
      };
      
      const code = await smsManager.getLatestCode(userInfo);
      console.log(`✅ 授权访问 /get_code from ${clientIP} at ${beijingTime.formatted}`);
      
      return new Response(JSON.stringify({
        code: code || '',
        status: code ? 'success' : 'waiting',
        timestamp: beijingTime.formatted,
        beijing_time: beijingTime.iso,
        message: code ? `获取到验证码: ${code}` : '暂无可用验证码',
        client_info: {
          ip: clientIP,
          access_time: beijingTime.formatted
        }
      }), { headers: corsHeaders });
    }

    // 状态查询 - 调试用
    if (url.pathname === '/status' && method === 'GET') {
      const status = await smsManager.getStatus();
      const usageStats = await smsManager.getUsageStats();
      const beijingTime = getBeijingTime();
      
      return new Response(JSON.stringify({
        status: 'running',
        service_time: beijingTime.formatted,
        beijing_time: beijingTime.iso,
        sms_service: status,
        usage_stats: usageStats,
        endpoints: {
          'POST /sms': '接收短信验证码（iOS Loon调用）',
          'GET /get_code?token=TOKEN': '获取最新验证码（Automa调用，需要token）',
          'GET /status': '查看服务状态',
          'GET /': '服务主页'
        }
      }), { headers: corsHeaders });
    }

    // 根路径 - 服务信息页面
    if (url.pathname === '/' && method === 'GET') {
      if (DEBUG_MODE) {
        console.log(`🏠 首页访问 - 开始获取状态`);
      }
      const status = await smsManager.getStatus();
      if (DEBUG_MODE) {
        console.log(`🏠 获取到状态: total=${status.total}, available=${status.available}`);
      }
      const usageStats = await smsManager.getUsageStats();
      const beijingTime = getBeijingTime();
      const html = `
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>📱 SMS验证码服务运行中</title>
          <style>
            body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; margin: 40px; background: #f5f5f5; }
            .container { max-width: 1000px; margin: 0 auto; background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
            h1 { color: #333; border-bottom: 2px solid #007bff; padding-bottom: 10px; }
            h2 { color: #555; margin-top: 30px; }
            .endpoint { background: #f8f9fa; padding: 15px; margin: 10px 0; border-radius: 5px; border-left: 4px solid #007bff; }
            .status { background: #d4edda; padding: 15px; border-radius: 5px; margin: 20px 0; }
            .usage-stats { background: #e7f3ff; padding: 15px; border-radius: 5px; margin: 20px 0; border-left: 4px solid #007bff; }
            .code { background: #e2e3e5; padding: 2px 6px; border-radius: 3px; font-family: monospace; }
            .countdown { color: #dc3545; font-weight: bold; }
            .expired { color: #6c757d; text-decoration: line-through; }
            ul { list-style-type: none; padding: 0; }
            li { margin: 10px 0; padding: 8px; background: #f8f9fa; border-radius: 4px; }
            .refresh { float: right; color: #007bff; cursor: pointer; }
            .time-info { color: #666; font-size: 0.9em; }
            .grid { display: grid; grid-template-columns: 1fr 1fr 0.8fr; gap: 20px; }
            .section { background: #f8f9fa; padding: 15px; border-radius: 5px; }
            .used-item { background: #d1ecf1; border-left: 3px solid #bee5eb; }
            .unused-item { background: #fff3cd; border-left: 3px solid #ffeaa7; }
            .ip-info { font-size: 0.8em; color: #666; }
          </style>
        </head>
        <body>
          <div class="container">
            <h1>📱 SMS验证码服务运行中 <span class="refresh" onclick="location.reload()">🔄</span></h1>
            
            <div class="status">
              <strong>🕐 服务时间:</strong> ${beijingTime.formatted} <span class="time-info">(北京时间)</span> | 
              <strong>⏱️ 下次刷新:</strong> <span id="refresh-countdown">10</span>秒<br>
              <strong>📊 验证码状态:</strong> 总计 ${status.total} 条，可用 ${status.available} 条<br>
              <strong>🌍 实例信息:</strong> <span class="code">${Deno.env.get('DENO_REGION') || 'unknown'}</span> | 
              <strong>🔑 访问令牌:</strong> <span class="code">********</span>
              ${DEBUG_MODE ? `<br><strong>🔍 调试信息:</strong> 原始验证码数据: ${JSON.stringify(status.codes.slice(0, 2))}` : ''}
            </div>

            <div class="grid">
              <div class="section">
                <h2>⏳ 待使用验证码</h2>
                <div id="pending-codes">
                  ${status.codes.filter(sms => !sms.used && !sms.expired).length > 0 ? 
                    status.codes.filter(sms => !sms.used && !sms.expired).map(sms => 
                      `<li class="unused-item" data-remaining="${sms.remainingTime}">
                        🔢 <span class="code">${sms.code}</span> | 📞 ${sms.sender}<br>
                        ⏰ 收到时间: ${sms.timestamp}<br>
                        <span class="countdown" id="countdown-${sms.code}">
                          ⏳ 剩余: ${Math.floor(sms.remainingTime/60)}分${sms.remainingTime%60}秒
                        </span>
                      </li>`
                    ).join('') 
                    : '<p>暂无待使用验证码</p>'
                  }
                </div>
              </div>

              <div class="section">
                <h2>📈 24小时使用概况</h2>
                <div class="usage-stats">
                  <strong>📊 统计数据:</strong> 总计 ${usageStats.total} 条，已使用 ${usageStats.used.count} 条，未使用 ${usageStats.unused.count} 条<br>
                  <small style="color: #666;">时间范围: ${getBeijingTime(Date.now() - 24*60*60*1000).formatted} - ${beijingTime.formatted}</small>
                </div>
                
                <h3>✅ 已使用 (${usageStats.used.count})</h3>
                <div style="max-height: 200px; overflow-y: auto;">
                  ${usageStats.used.codes.length > 0 ? 
                    usageStats.used.codes.map(sms => 
                      `<li class="used-item">
                        🔢 <span class="code">${sms.code}</span> | 📞 ${sms.sender}<br>
                        📥 收到: ${sms.receivedAt}<br>
                        🎯 使用: ${sms.usedAt}<br>
                        <span class="ip-info">
                          🌐 IP: ${sms.usedBy.ip}<br>
                          📱 客户端: ${sms.usedBy.userAgent}
                        </span>
                      </li>`
                    ).join('') 
                    : '<p>暂无已使用记录</p>'
                  }
                </div>

                <h3>⏳ 未使用 (${usageStats.unused.count})</h3>
                <div style="max-height: 200px; overflow-y: auto;">
                  ${usageStats.unused.codes.length > 0 ? 
                    usageStats.unused.codes.map(sms => 
                      `<li class="unused-item">
                        🔢 <span class="code">${sms.code}</span> | 📞 ${sms.sender}<br>
                        📥 收到: ${sms.receivedAt}<br>
                        ⏰ 过期: ${sms.expiresAt}<br>
                        <span class="countdown">
                          ⏳ 剩余: ${Math.floor(sms.remainingSeconds/60)}分${sms.remainingSeconds%60}秒
                        </span>
                      </li>`
                    ).join('') 
                    : '<p>暂无未使用记录</p>'
                  }
                </div>

              </div>

              <div class="section">
                <h2>⚠️ 已过期验证码</h2>
                <div style="max-height: 400px; overflow-y: auto;">
                  ${status.codes.filter(sms => !sms.used && sms.expired).slice(0, 5).length > 0 ? 
                    status.codes.filter(sms => !sms.used && sms.expired).slice(0, 5).map(sms => 
                      `<li class="expired" style="background: #f8d7da; border-left: 3px solid #dc3545; margin-bottom: 10px;">
                        🔢 <span class="code">${sms.code}</span><br>
                        📞 ${sms.sender}<br>
                        📥 ${sms.timestamp}<br>
                        ⚠️ ${sms.expiredDuration}
                      </li>`
                    ).join('') 
                    : '<p>暂无过期记录</p>'
                  }
                  ${status.codes.filter(sms => !sms.used && sms.expired).length > 5 ? 
                    `<p style="text-align: center; color: #666; font-size: 0.9em;">
                      还有 ${status.codes.filter(sms => !sms.used && sms.expired).length - 5} 条过期记录...
                    </p>` : ''
                  }
                </div>
              </div>
            </div>

            <h2>🔗 API端点:</h2>
            <div class="endpoint">
              <strong>POST /sms</strong> - 接收短信验证码<br>
              <small>iOS Loon + getsms.js 调用此接口推送短信</small>
            </div>
            <div class="endpoint">
              <strong>GET /get_code?token=TOKEN</strong> - 获取最新验证码<br>
              <small>⚠️ 需要访问令牌！Automa 工作流调用此接口获取验证码</small>
            </div>
            <div class="endpoint">
              <strong>GET /status</strong> - 查看服务状态<br>
              <small>返回JSON格式的详细状态信息</small>
            </div>

            <h2>🛠 配置说明:</h2>
            <p><strong>iOS Loon 配置:</strong></p>
            <ul>
              <li>通知方式: 辰星短信</li>
              <li>token/key: <span class="code">fysms.deno.dev</span></li>
            </ul>
            
            <p><strong>⚠️ Automa HTTP 请求（重要更新）:</strong></p>
            <ul>
              <li>URL: <span class="code">https://fysms.deno.dev/get_code?token=********</span></li>
              <li>方法: GET</li>
              <li>数据路径: <span class="code">code</span></li>
              <li><strong style="color: red;">注意：现在需要添加token参数！</strong></li>
              <li><strong style="color: blue;">请联系管理员获取实际token</strong></li>
            </ul>
            
            <div class="time-info">
              <p><strong>时区说明:</strong> 所有时间均为北京时间 (UTC+8)</p>
              <p><strong>安全说明:</strong> 验证码显示已加密，获取接口已添加访问令牌保护</p>
              <p><strong>存储说明:</strong> 验证码使用Deno KV持久化存储，支持跨区域访问，自动30天过期</p>
              <p><strong>使用逻辑:</strong> 验证码被获取后立即标记为已使用并失效，仅作为历史记录保存</p>
            </div>
          </div>

          <script>
            let refreshCountdown = 10;
            
            // 倒计时更新函数
            function updateCountdowns() {
              const pendingCodes = document.querySelectorAll('#pending-codes li[data-remaining]');
              pendingCodes.forEach(item => {
                const remaining = parseInt(item.dataset.remaining);
                if (remaining > 0) {
                  const newRemaining = remaining - 1;
                  item.dataset.remaining = newRemaining;
                  
                  const countdownElement = item.querySelector('.countdown');
                  if (newRemaining <= 0) {
                    countdownElement.textContent = '⚠️ 已过期';
                    countdownElement.className = 'expired';
                    item.className = item.className.replace('unused-item', 'expired');
                  } else {
                    const minutes = Math.floor(newRemaining / 60);
                    const seconds = newRemaining % 60;
                    countdownElement.textContent = \`⏳ 剩余: \${minutes}分\${seconds}秒\`;
                  }
                }
              });
            }

            // 刷新倒计时更新函数
            function updateRefreshCountdown() {
              const countdownElement = document.getElementById('refresh-countdown');
              if (countdownElement) {
                countdownElement.textContent = refreshCountdown;
                refreshCountdown--;
                
                if (refreshCountdown < 0) {
                  location.reload();
                }
              }
            }

            // 每秒更新倒计时
            setInterval(updateCountdowns, 1000);
            
            // 每秒更新刷新倒计时
            setInterval(updateRefreshCountdown, 1000);

            console.log('📱 SMS验证码服务页面已加载，倒计时功能已启动');
          </script>
        </body>
        </html>
      `;
      
      return new Response(html, { 
        headers: { 'Content-Type': 'text/html; charset=utf-8' } 
      });
    }

    // 404处理
    return new Response(JSON.stringify({
      error: 'Not Found',
      path: url.pathname,
      method: method,
      timestamp: getBeijingTime().formatted,
      available_endpoints: ['/sms', '/get_code', '/status', '/']
    }), { 
      status: 404, 
      headers: corsHeaders 
    });

  } catch (error) {
    console.error('❌ 请求处理错误:', error);
    const beijingTime = getBeijingTime();
    return new Response(JSON.stringify({
      error: '服务器内部错误',
      message: error.message,
      timestamp: beijingTime.formatted,
      beijing_time: beijingTime.iso
    }), { 
      status: 500, 
      headers: corsHeaders 
    });
  }
}

// Deno Deploy 入口点
Deno.serve(handleRequest); 